import React, {useEffect, useState} from 'react';
import {View, Text, StyleSheet, Image, TouchableOpacity} from 'react-native';
import avator from "@/assets/images/me/avator.png";
import { useUserStore } from "@/hooks/im/user";
import { useNavigation, useRouter } from "expo-router";
import { useConversationStore } from "@/hooks/im/conversation"
import dayjs from "dayjs";
import { messageformatDateTime } from "@/utils/index"
import { Image as ExpoImage } from 'react-native-expo-image-cache';
import {useSelector} from "react-redux";
import {RootState} from "@/store";

const ChatItem = ({ item }) => {
    // console.log('itemitemitemitemitemitem', item)
    const { sendID, textElem, senderNickname, showName, showTime, createTime, contentType, notificationElem, recvID, faceUrl, senderFaceUrl, sessionType } = item.item;

    const selfUserID = useUserStore((state) => state.selfInfo.userID);
    const currentConversation = useConversationStore((state) => state.currentConversation);
    const currentGroupList = useConversationStore((state) => state.currentGroupList);

    const login = useSelector((state: RootState) => state.login);

    const isSender = login.userInfo.uid === sendID;

    const navigation = useNavigation();

    const router = useRouter();

    useEffect(() => {

    }, [login.userInfo])

    useEffect(() => {
        setTimeout(() => {
            // console.log('currentConversation', currentConversation);
            if (currentConversation?.conversationType == 3) {
                navigation.setOptions({ title: currentConversation?.showName + `(${currentGroupList.length})` })
            } else if (currentConversation?.conversationType == 1) {
                navigation.setOptions({ title: currentConversation?.showName });
            };

        }, 100)
    }, [navigation])

    const goProfile = function () {
        router.push("/profile")
    };

    return (
        <View style={{ paddingBottom: 15, }}>
            {
                showTime && (
                    <View style={styles.msgDate}>
                        <Text style={styles.msgDateText}>
                            <Text style={styles.createTimeGroupChatLightText}>
                                { messageformatDateTime(createTime) }
                            </Text>
                        </Text>
                    </View>
                )
            }
            {
                //群创建通知
                contentType == 1501 && (
                    <View style={styles.createGroupChat}>
                        <Text style={styles.createGroupChatText}>
                            <Text style={styles.createGroupChatLightText}>
                                { JSON.parse(notificationElem.detail).opUser.nickname }
                            </Text>
                            创建了群聊</Text>
                    </View>
                )
            }

            {
                //双方成为好友通知
                contentType == 1201 && (
                    <View style={styles.createGroupChat}>
                        <Text style={styles.createGroupChatText}>
                            你们已经成为好友，可以开始聊天了！
                        </Text>
                    </View>
                )
            }

            {
                //群成员退出通知
                contentType == 1504 && (
                    <View style={styles.createGroupChat}>
                        <Text style={styles.createGroupChatText}>
                            <Text style={styles.createGroupChatLightText}>
                                { JSON.parse(notificationElem.detail).quitUser.nickname }
                            </Text>
                            退出了群聊</Text>
                    </View>
                )
            }

            {
                //邀请群成员通知
                contentType == 1509 && (
                    <View style={styles.createGroupChat}>
                        <Text style={styles.createGroupChatText}>
                            <Text style={styles.createGroupChatLightText}>{ JSON.parse(notificationElem.detail).opUser.nickname }</Text>
                             邀请了
                            {
                                JSON.parse(notificationElem.detail).invitedUserList.map((item, index) => {
                                    return <Text style={styles.createGroupChatLightText}>{ item.nickname } { JSON.parse(notificationElem.detail).invitedUserList.length - 1 !== index ? '、' : "" }</Text>
                                })
                            }
                            加入群聊
                        </Text>
                    </View>
                )
            }

            {
                //群成员被踢通知
                contentType == 1508 && (
                    <View style={styles.createGroupChat}>
                        <Text style={styles.createGroupChatText}>
                            {
                                JSON.parse(notificationElem.detail).kickedUserList.map((item, index) => {
                                    return <Text style={styles.createGroupChatLightText}>{ item.nickname } { JSON.parse(notificationElem.detail).kickedUserList.length - 1 !== index ? '、' : "" }</Text>
                                })
                            }
                            被
                            <Text style={styles.createGroupChatLightText}>{ JSON.parse(notificationElem.detail).opUser.nickname }</Text>
                            踢出群聊
                        </Text>
                    </View>
                )
            }

            {
                //解散群通知
                contentType == 1511 && (
                    <View style={styles.createGroupChat}>
                        <Text style={styles.createGroupChatText}>

                            <Text style={styles.createGroupChatLightText}>{ JSON.parse(notificationElem.detail).opUser.nickname }</Text>
                            解散了群聊</Text>
                    </View>
                )
            }


            {
                //文本消息
                contentType == 101 && (
                    <View
                        style={[
                            styles.container,
                            isSender ? styles.ownMessageContainer : styles.otherMessageContainer,
                        ]}
                    >
                        {!isSender && (
                            <TouchableOpacity onPress={goProfile}>
                                <Image source={{ uri: senderFaceUrl }} style={styles.avatar} />
                            </TouchableOpacity>
                        )}

                        <View style={styles.contentRightWrap}>
                            <View style={[styles.header]}>
                                {!isSender && sessionType == 3 && <Text style={styles.nickname}>{senderNickname}</Text>}
                            </View>
                            <View
                                style={[
                                    !isSender ? styles.leftContent : styles.rightContent,
                                    isSender ? styles.ownMessageContent : styles.otherMessageContent,
                                ]}
                            >
                                <Text style={[  isSender ? styles.ownMessageText : styles.otherMessageText]}>{textElem?.content}</Text>
                            </View>
                        </View>

                        {isSender && (
                            <Image source={{ uri: login.userInfo.avatarUrl  }} style={styles.avatar} />
                        )}
                    </View>
                )
            }
            {
                //图片消息
                contentType == 102 && (
                    <View
                        style={[
                            styles.container,
                            isSender ? styles.ownMessageContainer : styles.otherMessageContainer,
                        ]}
                    >
                        {!isSender && <Image source={{ uri: senderFaceUrl}} style={styles.avatar} />}
                        <View style={styles.contentRightWrap}>
                            <View style={styles.header}>
                                {!isSender && sessionType == 3 && <Text style={styles.nickname}>{senderNickname}</Text>}
                            </View>
                            {/*<View*/}
                            {/*    style={[*/}
                            {/*        !isSender ? styles.leftContent : styles.rightContent,*/}
                            {/*        isSender ? styles.ownMessageContent : styles.otherMessageContent,*/}
                            {/*    ]}*/}
                            {/*>*/}
                            {/*    <Text>{ item.item.pictureElem.bigPicture.url }</Text>*/}
                            {/*</View>*/}
                            <ExpoImage
                                // source={{ uri: item.item.pictureElem.bigPicture.url }}
                                style={{ marginRight: 5, width: item.item.pictureElem.bigPicture.width, height: item.item.pictureElem.bigPicture.height }}
                                resizeMode='contain'
                                uri={item?.item.pictureElem.bigPicture.url}
                            />
                        </View>

                        {isSender && <Image source={{ uri: faceUrl || senderFaceUrl }} style={styles.avatar} />}
                    </View>
                )
            }

            {
                // 群公告改变通知
                contentType == 1519 && (
                    <View
                        style={[
                            styles.container,
                            isSender ? styles.ownMessageContainer : styles.otherMessageContainer,
                        ]}
                    >
                        {!isSender && <Image source={avator} style={styles.avatar} />}
                        <View style={styles.contentRightWrap}>
                            <View style={styles.header}>
                                {!isSender && sessionType == 3 && <Text style={styles.nickname}>{senderNickname}</Text>}
                            </View>
                            <View
                                style={[
                                    !isSender ? styles.leftContent : styles.rightContent,
                                    isSender ? styles.ownMessageContent : styles.otherMessageContent,
                                ]}
                            >
                                <View>
                                    <Text style={[!isSender ? styles.noticeTitleLeft : styles.noticeTitleRight ]}>群公告</Text>
                                </View>
                                <Text style={[ isSender ? styles.ownMessageText : styles.otherMessageText]}>{JSON.parse(notificationElem.detail).group.notification}</Text>
                            </View>
                        </View>

                        {isSender && <Image source={{ uri: faceUrl }} style={styles.avatar} />}
                    </View>
                )
            }
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        padding: 10,
        alignItems: 'flex-start',
    },
    ownMessageContainer: {
        justifyContent: 'flex-end',
    },
    otherMessageContainer: {
        justifyContent: 'flex-start',
    },
    avatar: {
        width: 40,
        height: 40,
        borderRadius: 20,
    },
    leftContent: {
        alignSelf: 'flex-start',
        maxWidth: 280,
        padding: 13,
        borderTopRightRadius: 10,
        borderBottomLeftRadius: 10,
        borderBottomRightRadius: 10,
        minWidth: 0,

    },
    rightContent: {
        maxWidth: 280,
        padding: 13,
        borderTopLeftRadius:10,
        borderBottomLeftRadius: 10,
        borderBottomRightRadius: 10,
    },
    ownMessageContent: {
        backgroundColor: '#EC6138',
        // alignItems: 'flex-end',
        marginRight: 10,
    },
    otherMessageContent: {
        backgroundColor: '#FFF',
        alignItems: 'flex-start',

    },
    header: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginBottom: 5,

    },
    nickname: {
        color: "#9C9EAC",
        fontSize: 12,
        flexDirection: "row",
    },
    time: {
        fontSize: 12,
        color: '#888',
    },
    message: {
        fontSize: 14,
        color: '#333',
    },
    ownMessageText: {
        fontSize: 14,
        color: '#FFF',
        lineHeight: 20,
    },
    otherMessageText: {
        fontSize: 14,
        color: '#2A2B30',
        lineHeight: 20,
    },
    contentRightWrap: {
        marginLeft:10,
    },
    msgDate: {
        marginVertical: 15
    },
    msgDateText: {
        textAlign: "center",
        color: "#C0C3CE",
        fontSize: 12,
    },
    createGroupChat: {

    },
    createGroupChatText: {
        textAlign: "center",
        fontSize: 12,
        color: "#8e9ab0",
    },
    createTimeGroupChatLightText: {
        color: "#C0C3CE",
    },
    createGroupChatLightText: {
        color: "#EC6138"
    },
    noticeTitleLeft: {
        textAlign: "left",
        color: "#000"
    },
    noticeTitleRight: {
        color: "#FFF"
    },
});

export default ChatItem;
